<template>
  <div class="login-container">
    <div class="login-box">
      <h2>用户登录</h2>
      <form @submit.prevent="login">
        <div class="input-group">
          <label for="username">用户名:</label>
          <input type="text" id="username" v-model="username" required />
        </div>
        <div class="input-group">
          <label for="password">密码:</label>
          <input type="password" id="password" v-model="password" required />
        </div>
        <button type="submit" class="login-btn">登录</button>
      </form>
      <p v-if="errorMsg" class="error-msg">{{ errorMsg }}</p>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import api from '../api/api';
import { useRouter } from 'vue-router'
import { useAuthStore } from '../stores/authStore'

const username = ref('');
const password = ref('');
const errorMsg = ref('');

const router = useRouter()
const authStore = useAuthStore()
const login = async () => {
  try {
    const response = await api.post('/login/auth', {
      username: username.value,
      password: password.value
    });

    const { code, msg, data } = response.data;
    if (code === 1 && msg === 'success') {
      const info = data;
      authStore.login({
        token: info.token,
        id: info.id,
        username: info.username
      })
      alert(`登录成功，欢迎 ${info.username}！`);
      // 登录成功后跳转到文章列表界面
      window.location.href = '/articles';
    } else {
      errorMsg.value = '登录失败请重试.';
    }
  } catch (error) {
    console.error('发生错误:', error);
    errorMsg.value = '发生了错误请重试.';
  }
};
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: #f0f2f5;
}

.login-box {
  background: white;
  padding: 30px 40px;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  width: 100%;
  max-width: 400px;
  box-sizing: border-box;
}

h2 {
  text-align: center;
  margin-bottom: 20px;
  color: #333;
}

.input-group {
  margin-bottom: 15px;
}

.input-group label {
  font-weight: bold;
  display: block;
  margin-bottom: 6px;
}

.input-group input {
  width: 100%;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 6px;
  font-size: 14px;
  transition: border-color 0.3s ease;
}

.input-group input:focus {
  border-color: #007bff;
  outline: none;
  box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.2);
}

.login-btn {
  width: 100%;
  padding: 12px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.login-btn:hover {
  background-color: #0056b3;
}

.error-msg {
  color: red;
  text-align: center;
  margin-top: 15px;
}
</style>